package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasListGroupEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasListGroupEntityExt;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.group.impl.ProListGroupServiceImpl;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.model.PaasListGroupModel;
import com.xbongbong.paas.pojo.dto.ExplainScreenListDTO;
import com.xbongbong.paas.pojo.dto.ListGroupAddDTO;
import com.xbongbong.paas.pojo.dto.ListGroupDeleteDTO;
import com.xbongbong.paas.pojo.dto.ListGroupExplainDTO;
import com.xbongbong.paas.pojo.dto.ListGroupGetDTO;
import com.xbongbong.paas.pojo.dto.ListGroupListDTO;
import com.xbongbong.paas.pojo.dto.ListGroupSortDTO;
import com.xbongbong.paas.pojo.dto.ListGroupUpdateDTO;
import com.xbongbong.paas.pojo.vo.ExplainScreenListVO;
import com.xbongbong.paas.pojo.vo.GroupListVO;
import com.xbongbong.paas.pojo.vo.ListGroupAddVO;
import com.xbongbong.paas.pojo.vo.ListGroupDeleteVO;
import com.xbongbong.paas.pojo.vo.ListGroupExplainVO;
import com.xbongbong.paas.pojo.vo.ListGroupGetVO;
import com.xbongbong.paas.pojo.vo.ListGroupSortVO;
import com.xbongbong.paas.pojo.vo.ListGroupUpdateVO;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.PaasListGroupService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.GroupErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.script.pojo.vo.ScriptVO;
import com.xbongbong.saas.domain.entity.PublicGroupEntity;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.model.PublicGroupModel;
import com.xbongbong.saas.service.PublicGroupService;
import com.xbongbong.sys.domain.entity.UserEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: wufeng
 * @date: 2018/9/7 15:30
 * @desrcption: 分组管理接口实现
 */
@Service("paasListGroupService")
public class PaasListGroupServiceImpl implements PaasListGroupService {

    private static final Logger LOG = LoggerFactory.getLogger(PaasListGroupServiceImpl.class);



    @Resource
    private PaasListGroupModel paasListGroupModel;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private PublicGroupService publicGroupService;
    @Resource
    private PublicGroupModel publicGroupModel;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private ProListGroupServiceImpl proListGroupService;
    @Resource
    private CommonHelp commonHelp;

    @Override
    public GroupListVO  list(ListGroupListDTO groupListDTO) throws XbbException {
        return proListGroupService.list(groupListDTO);

    }




    @Override
    public ListGroupAddVO add(ListGroupAddDTO listGroupAddDTO) throws XbbException {
       return proListGroupService.add(listGroupAddDTO);
    }

    @Override
    public ListGroupUpdateVO update(ListGroupUpdateDTO listGroupUpdateDTO) throws XbbException {
        ListGroupUpdateVO listGroupUpdateVO = new ListGroupUpdateVO();
        try {
            PaasListGroupEntity entity = paasListGroupModel.getByKey(listGroupUpdateDTO.getListGroupId(), listGroupUpdateDTO.getCorpid());
            if (entity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LIST_GROUP_NOT_EXIST);
            }
            if (entity.getDefaultGroupCode() > 0){
                //TODO haibin.zhang 默认不允许更新
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LIST_GROUP_NOT_EXIST);
            }
            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("corpid",listGroupUpdateDTO.getCorpid());
            map.put("formId",listGroupUpdateDTO.getFormId());
            map.put("creatorId",listGroupUpdateDTO.getUserId());
            map.put("name",listGroupUpdateDTO.getName());
            map.put("del",0);
            map.put("negId",listGroupUpdateDTO.getListGroupId());
            Integer repeatCount = paasListGroupModel.getEntitysCount(map);
            if (repeatCount > 0){
                throw new XbbException(GroupErrorCodeEnum.API_ERROR_351001, GroupErrorCodeEnum.API_ERROR_351001.getMsg());
            }
            PaasListGroupEntity paasListGroupEntity = new PaasListGroupEntity();
            BeanUtil.copyProperties(listGroupUpdateDTO, paasListGroupEntity);
            paasListGroupEntity.setJsonData(JSONArray.toJSONString(listGroupUpdateDTO.getData()));
            paasListGroupEntity.setId(listGroupUpdateDTO.getListGroupId());
            paasListGroupModel.update(paasListGroupEntity);

            listGroupUpdateVO.setListGroupId(listGroupUpdateDTO.getListGroupId());
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("listGroup数据库增加列表分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return listGroupUpdateVO;
    }

    @Override
    public ListGroupDeleteVO delete(ListGroupDeleteDTO listGroupDeleteDTO) throws XbbException {
        ListGroupDeleteVO listGroupDeleteVO = new ListGroupDeleteVO();
        try {
            PaasListGroupEntity entity = paasListGroupModel.getByKey(listGroupDeleteDTO.getListGroupId(), listGroupDeleteDTO.getCorpid());
            if (entity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LIST_GROUP_NOT_EXIST);
            }
            PaasListGroupEntity paasListGroupEntity = paasListGroupModel.getByKey(listGroupDeleteDTO.getListGroupId(),listGroupDeleteDTO.getCorpid());
            if (paasListGroupEntity == null || paasListGroupEntity.getDefaultGroupCode() > 0){
                //TODO haibin.zhang 默认分组删除
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, "沙雕月月月月");
            }
            paasListGroupEntity.setDel(1);
            paasListGroupModel.update(paasListGroupEntity);

            listGroupDeleteVO.setListGroupId(listGroupDeleteDTO.getListGroupId());
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("listGroup数据库增加列表分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return listGroupDeleteVO;
    }

    @Override
    public ListGroupGetVO get(ListGroupGetDTO listGroupGetDTO) throws XbbException {

        ListGroupGetVO listGroupGetVO = new ListGroupGetVO();
        try {
            PaasListGroupEntity entity = paasListGroupModel.getByKey(listGroupGetDTO.getListGroupId(), listGroupGetDTO.getCorpid());
            if (entity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LIST_GROUP_NOT_EXIST);
            }
            PaasListGroupEntityExt paasListGroupEntityExt = new PaasListGroupEntityExt();
            BeanUtil.copyProperties(entity, paasListGroupEntityExt);
            //阶段推进器和原客户、机会、线索阶段分组的条件数据格式不同，这一步将老格式转化为新格式
            formatStageCondition(entity, listGroupGetDTO.getSaasMark(), listGroupGetDTO.getBusinessType());
            paasListGroupEntityExt.setConditionList(entity.getJsonData());
            paasListGroupEntityExt.setJsonData("");
            listGroupGetVO.setListGroup(paasListGroupEntityExt);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("listGroup数据库增加列表分组出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return listGroupGetVO;
    }

    /**
     * 将原客户，线索，机会的阶段分组数据格式转化为阶段推进器的新数据格式
     * @param entity
     * @param saasMark
     * @param businessType
     * @throws XbbException
     */
    private void formatStageCondition(PaasListGroupEntity entity,  Integer saasMark, Integer businessType) throws XbbException {
        String jsonData = entity.getJsonData();
        Long formId = entity.getFormId();
        String corpid = entity.getCorpid();
        try {
            //只有客户线索机会这三张表单会有阶段分组的历史数据
            if (Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode())) {
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())
                        || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {

                    PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, formId, businessType);
                    Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains(), null);

                    List<ConditionsEntityExt> conditions = JSONArray.parseArray(jsonData, ConditionsEntityExt.class);
                    for (ConditionsEntityExt condition : conditions) {
                        //规避历史客户线索机会阶段fieldType是3的情况
                        Integer conditionFieldType = explainMap.get(condition.getAttr()).getFieldType();
                        if (Objects.equals(conditionFieldType, FieldTypeEnum.STAGE_THRUSTER.getType()) && CollectionsUtil.isNotEmpty(condition.getValue())) {
                            List<Object> value = condition.getValue();
                            String conditionSymbol = condition.getSymbol();

                            if (Objects.equals(condition.getSymbol(), ConditionEnum.EQUAL.getSymbol()) || Objects.equals(condition.getSymbol(), ConditionEnum.NOEQUAL.getSymbol())) {
                                //客户线索机会历史阶段分组数据code是数字类型，这里需要转换成字符串
                                value.set(0, String.valueOf(value.get(0)));
                            } else if (Objects.equals(conditionSymbol, ConditionEnum.IN.getSymbol()) || Objects.equals(conditionSymbol, ConditionEnum.NOIN.getSymbol())) {
                                for (int i = 0; i < value.size(); i++) {
                                    value.set(i, String.valueOf(value.get(i)));
                                }
                            }
                            condition.setValue(value);
                            condition.setFieldType(conditionFieldType);
                        }
                    }
                    entity.setJsonData(JSON.toJSONString(conditions));
                }
            }
        } catch (Exception e) {
            LOG.error("PaasListGroupServiceImpl.formatStageCondition出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public ListGroupExplainVO getExplain(ListGroupExplainDTO listGroupExplainDTO) throws XbbException {
        ListGroupExplainVO listGroupExplainVO = new ListGroupExplainVO();
        try {
            ExplainScreenListDTO explainScreenListDTO = new ExplainScreenListDTO();
            BeanUtil.copyProperties(listGroupExplainDTO, explainScreenListDTO);
            ExplainScreenListVO explainScreenListVO = paasFormExplainService.screenList(explainScreenListDTO);
            if(explainScreenListVO == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            listGroupExplainVO.setFormExplainList(explainScreenListVO.getFormExplainList());
        } catch (Exception e) {
            LOG.error("listGroup获取当前表单的适合列表分组字段列表出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return listGroupExplainVO;
    }

    @Override
    public ListGroupSortVO sort(ListGroupSortDTO listGroupSortDTO) throws XbbException {
        return proListGroupService.sort(listGroupSortDTO);
    }

    @Override
    public GroupListVO publicList(ListGroupListDTO groupListDTO) throws XbbException{
        UserEntity userEntity = new UserEntity();
        BeanUtil.copyProperties(groupListDTO.getLoginUser(),userEntity);
        boolean isBoss = groupListDTO.getLoginUser().isAdminOrBoss();
        boolean maxDataPermission = groupListDTO.getLoginUser().isMaxDataPermission();
        List<PublicGroupEntity> publicGroupEntityList;
        if(isBoss || maxDataPermission) {
            publicGroupEntityList = publicGroupModel.enableListByFormId(groupListDTO.getCorpid(), groupListDTO.getFormId());
        } else {
            publicGroupEntityList = publicGroupService.getListByUser(userEntity,groupListDTO.getFormId());
        }

        List<PaasListGroupEntityExt> paasListGroupEntityExtList = new ArrayList<>();
        //设置全部分组
        PaasListGroupEntityExt allPublicGroup = new PaasListGroupEntityExt(ListGroupEnum.ALL);
        allPublicGroup.setDefaultGroup(2);
        paasListGroupEntityExtList.add(allPublicGroup);
        for (PublicGroupEntity publicGroupEntity : publicGroupEntityList){
            PaasListGroupEntityExt paasListGroupEntityExt = new PaasListGroupEntityExt();
            paasListGroupEntityExt.setName(publicGroupEntity.getName());
            paasListGroupEntityExt.setId(publicGroupEntity.getId());
            paasListGroupEntityExt.setDefaultGroup(2);
            paasListGroupEntityExtList.add(paasListGroupEntityExt);
        }

        // 新版工作流开启 而且 业务支持审批时展示【审批中】分组
        boolean isOpenWorkflow = commonHelp.isOpenWorkFlow(groupListDTO.getCorpid());
        if (isOpenWorkflow) {
            PaasListGroupEntityExt paasListGroupEntityExt = new PaasListGroupEntityExt(ListGroupEnum.APPROVAL);
            paasListGroupEntityExt.setDefaultAlias(ListGroupEnum.APPROVAL.getAlias());
            paasListGroupEntityExtList.add(paasListGroupEntityExt);
        }

        GroupListVO groupListVO = new GroupListVO();
        groupListVO.setListGroupList(paasListGroupEntityExtList);
        groupListVO.setShowSetting(false);
        proListGroupService.setSaasSwimLaneView(groupListVO, groupListDTO);return groupListVO;
    }
    
    @Override
    public ScriptVO deleteByGroup() throws XbbException{
        ScriptVO scriptVO = new ScriptVO();
        Integer count = paasListGroupModel.deleteByDefaultGroupCode();
        String msg = "您已经处理了" + count + "条数据";
        scriptVO.setMsg(msg);
        return scriptVO;
    }



}
